//
//  joystick.m
//  CommandCenter08
//
//  Created by Matt Roman on 7/7/08.
//  Copyright 2008 University of Oklahoma. All rights reserved.
//

#import "joystick.h"


@implementation joystick

- (id)initWithFrame:(NSRect)frameRect
{
	self = [super initWithFrame:frameRect];
	clientConnection = nil;
	return self;
}

- (void)setClientConnection:(NetClient*)cc
{
	clientConnection = cc;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Joystick actions
//////////////////////////////////////////////////////////////////////////////////////////
- (IBAction)turnLeft:(id)sender
{
	if(clientConnection)[clientConnection sendString:@"JoystickLeft" encoding:NSASCIIStringEncoding];
	//NSLog(@"turn left");
}
- (IBAction)turnRight:(id)sender
{
	if(clientConnection)[clientConnection sendString:@"JoystickRight" encoding:NSASCIIStringEncoding];
	//NSLog(@"turn right");
}
- (IBAction)driveForward:(id)sender
{
	if(clientConnection)[clientConnection sendString:@"JoystickForward" encoding:NSASCIIStringEncoding];
	//NSLog(@"forward");
}
- (IBAction)driveBackward:(id)sender
{
	if(clientConnection)[clientConnection sendString:@"JoystickBackward" encoding:NSASCIIStringEncoding];
	//NSLog(@"backward");
}
- (IBAction)stop:(id)sender
{
	if(clientConnection)[clientConnection sendString:@"Stop" encoding:NSASCIIStringEncoding];
	//NSLog(@"Stop");
}
- (void)keyDown:(NSEvent*)event
{
	unichar keyChar = 0;
	if([event modifierFlags] & NSNumericPadKeyMask){
		NSString *theArrow = [event charactersIgnoringModifiers];
		
		if([theArrow length] == 0) return;
		if([theArrow length] == 1){
			keyChar = [theArrow characterAtIndex:0];
			switch (keyChar) {
				case NSUpArrowFunctionKey:
					[self driveForward:self];
					break;
				case NSDownArrowFunctionKey:
					[self driveBackward:self];
					break;
				case NSLeftArrowFunctionKey:
					[self turnLeft:self];
					break;
				case NSRightArrowFunctionKey:
					[self turnRight:self];
					break;
				default:
					break;
			}
		}
	}
	else{
		NSString *keyStroke = [event charactersIgnoringModifiers];
		if([keyStroke length] == 0) return;
		if([keyStroke length] == 1){
			keyChar = [keyStroke characterAtIndex:0];
			switch(keyChar){
				case ' ':
					[self stop:self];
					break;
			}
		}
	}
	//[super keyDown:event];
}

- (BOOL)acceptsFirstResponder
{
	return YES;
}
- (BOOL)becomeFirstResponder
{
	return YES;
}
- (BOOL)resignFirstResponder
{
	return YES;
}
@end
